package com.aijk.commons.dubbo.cluster.loadbalance;

/**
 * Created by iscdw on 2016/4/13.
 */

import com.aijk.commons.exception.ErrorCodeException;
import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.dubbo.rpc.RpcException;
import com.alibaba.dubbo.rpc.cluster.loadbalance.RoundRobinLoadBalance;

import java.util.List;

/**
 * 根据owner参数指定调用服务端
 */
public class OwnerLoadBalance extends RoundRobinLoadBalance {

    @Override
    public <T> Invoker<T> select(List<Invoker<T>> list, URL url, Invocation invocation) throws RpcException {
        String to = String.valueOf(RpcContext.getContext().get("to"));
        for (Invoker<T> invoker : list) {
            if (invoker.getUrl().getParameter("owner").equals(to)) {
                return invoker;
            }
        }

        throw new ErrorCodeException(String.format("当前Owner不存在%s", to));
    }
}